package com.xj.zhihudemo.ui.activity;

import android.os.Bundle;
import android.support.design.widget.AppBarLayout;
import android.support.design.widget.Snackbar;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentTransaction;
import android.support.v4.view.GravityCompat;
import android.support.v4.widget.DrawerLayout;
import android.support.v7.app.ActionBarDrawerToggle;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.DefaultItemAnimator;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.support.v7.widget.Toolbar;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.FrameLayout;
import android.widget.LinearLayout;

import com.xj.zhihudemo.R;
import com.xj.zhihudemo.mode.MenuInfo;
import com.xj.zhihudemo.retrofit.ApiClient;
import com.xj.zhihudemo.retrofit.ApiStore;
import com.xj.zhihudemo.ui.adapter.MenuAdapter;
import com.xj.zhihudemo.ui.fragment.MainFragment;
import com.xj.zhihudemo.ui.fragment.ThemesFragment;
import com.xj.zhihudemo.utils.CustomItemDecoration;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;

import static android.view.View.OVER_SCROLL_NEVER;

public class MainActivity extends AppCompatActivity {

    private final String TAG = getClass().getSimpleName();
    @BindView(R.id.tool_bar)
    Toolbar mToolBar;
    @BindView(R.id.app_bar)
    AppBarLayout mAppBar;
    @BindView(R.id.main_content)
    FrameLayout mMainContent;
    @BindView(R.id.home_drawerLayout)
    DrawerLayout mHomeDrawerLayout;
    @BindView(R.id.center_adapt_status_bar)
    View mCenterAdaptStatusBar;
    @BindView(R.id.rv_menu)
    RecyclerView mRvMenu;
    private long firstBackPressedTime = 0;
    private ActionBarDrawerToggle mDrawerToggle;
    private MenuAdapter mMenuAdapter;
    private LinearLayoutManager mLayoutManager;
    private View mHeaderView;
    private List<MenuInfo.OthersEntity> mThemeList;
    private FragmentManager fragmentManager;
    private FragmentTransaction fragmentTransaction;
    private MainFragment mMainFragment;
    private ThemesFragment mThemesFragment;
    private LinearLayout mLinearLayoutHome;


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        Log.d(TAG, "onCreate");
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        mMenuAdapter = new MenuAdapter(this);
        mMainFragment = MainFragment.getInstance();
        mThemesFragment = ThemesFragment.getInstance();
        ButterKnife.bind(this);
        initData();
        initView(savedInstanceState);
        setDefaultFragment();


    }

    private void setDefaultFragment() {


        fragmentTransaction.add(R.id.main_content, mMainFragment);
        fragmentTransaction.commit();

    }

    /**
     * 初始化数据
     */
    protected void initData() {
        Log.d(TAG, "initData");
        mThemeList = new ArrayList<MenuInfo.OthersEntity>();
        ApiStore apiStore = ApiClient.retrofit().create(ApiStore.class);
        final Call<MenuInfo> menuInfoCall = apiStore.getMenu();
        menuInfoCall.enqueue(new Callback<MenuInfo>() {
            @Override
            public void onResponse(Call<MenuInfo> call, Response<MenuInfo> response) {
                Log.d(TAG, "onResponse");
                MenuInfo themesInfo = response.body();
                if (themesInfo != null) {
                    int limt = themesInfo.getLimit();
                    mThemeList.addAll(themesInfo.getOthers());
                    mMenuAdapter.addData(mThemeList);
                    Log.d(TAG, mThemeList.size() + "");
//                    ToastUtils.with(MainActivity.this).show();

                }

            }

            @Override
            public void onFailure(Call<MenuInfo> call, Throwable t) {

            }
        });


    }

    protected void initView(Bundle savedInstanceState) {
        Log.d(TAG, "initView()");

        fragmentManager = getSupportFragmentManager();
        fragmentTransaction = fragmentManager.beginTransaction();
        initToolBar();
        initMenu();
    }

    @Override
    protected void onResume() {
        super.onResume();
//        initData();
    }

    /**
     * 初始化菜单栏
     */
    private void initMenu() {
        mLayoutManager = new LinearLayoutManager(this, LinearLayoutManager.VERTICAL, false);
        mHeaderView = LayoutInflater.from(this).inflate(R.layout.layout_menu_header, null, false);
        mRvMenu.setLayoutManager(mLayoutManager);
        mRvMenu.setItemAnimator(new DefaultItemAnimator());
        mRvMenu.setOverScrollMode(OVER_SCROLL_NEVER);
        mRvMenu.addItemDecoration(new CustomItemDecoration(this, true));
        mRvMenu.setAdapter(mMenuAdapter);
        setHeader(mRvMenu);
        mMenuAdapter.setOnItemClickListener(new MenuAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(View view, int position, MenuInfo.OthersEntity data) {
                ThemesFragment themesFragment = new ThemesFragment();
                Bundle bundle = new Bundle();
                int themeId = data.getId();
                String toolbarTitle = data.getName();
                bundle.putInt("ID", themeId);
                themesFragment.setArguments(bundle);
                fragmentTransaction = fragmentManager.beginTransaction();
                fragmentTransaction.replace(R.id.main_content, themesFragment);
                fragmentTransaction.commit();
                mToolBar.setTitle(toolbarTitle);
                mHomeDrawerLayout.closeDrawers();
//                Toast.makeText(MainActivity.this, "Click " + position + "data" + data, Toast.LENGTH_SHORT).show();
            }

            @Override
            public void onItemLongClick(View view, int position, MenuInfo.OthersEntity data) {
//                Toast.makeText(MainActivity.this, "LongClick " + position + "data" + data, Toast.LENGTH_SHORT).show();
            }
        });
    }

    /**
     * 初始化ToolBar
     */
    private void initToolBar() {
        Log.d(TAG, "initToolBar");
        setSupportActionBar(mToolBar);
        mToolBar.setTitle("首页");
        getSupportActionBar().setHomeButtonEnabled(true);
        getSupportActionBar().setDisplayHomeAsUpEnabled(true);
        mDrawerToggle = new ActionBarDrawerToggle(this, mHomeDrawerLayout, mToolBar,
                R.string.open, R.string.close) {
            @Override
            public void onDrawerOpened(View drawerView) {
                super.onDrawerOpened(drawerView);
//                mAnimationDrawable.stop();
//                initMenu();
            }

            @Override
            public void onDrawerClosed(View drawerView) {
                super.onDrawerClosed(drawerView);
//                mAnimationDrawable.start();
            }
        };
        mDrawerToggle.syncState();
        mHomeDrawerLayout.setDrawerListener(mDrawerToggle);

    }

    private void setHeader(RecyclerView view) {
        View header = LayoutInflater.from(this).inflate(R.layout.layout_menu_header, view, false);
        mMenuAdapter.addHeaderView(header);
        mLinearLayoutHome = (LinearLayout) header.findViewById(R.id.ll_main_home);
        mLinearLayoutHome.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                fragmentTransaction = fragmentManager.beginTransaction();
                fragmentTransaction.replace(R.id.main_content, mMainFragment);
                fragmentTransaction.commit();
                mHomeDrawerLayout.closeDrawers();
                mToolBar.setTitle("首页");
            }
        });
    }

    /**
     * 点击返回按钮操作
     */
    @Override
    public void onBackPressed() {
        if (mHomeDrawerLayout.isDrawerOpen(GravityCompat.START)) {
            mHomeDrawerLayout.closeDrawer(GravityCompat.START);
        } else {
            long secondBackPressedTime = System.currentTimeMillis();
            if (secondBackPressedTime - firstBackPressedTime > 2000) {
                Snackbar.make(mMainContent, "再按一次退出", Snackbar.LENGTH_SHORT).show();
                firstBackPressedTime = secondBackPressedTime;
            } else {
                super.onBackPressed();
            }
        }
    }

}
